<?php

/**
 * Request helper
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    Kernel
 */

namespace Celebrio\Util;

use Nette\Object;
use Nette\Environment;

class RequestBuilder extends Object {
    
    private $request = "";
    private $requestBase = "";
    
    public function __construct($requestBase = "") {
        if(!empty($requestBase)) {
            $this->setRequestBase($requestBase);
        }
    }
    
    public function setRequestBase($requestBase) {
        $requestBase = $this->appendQuestionMark($requestBase);
        if($this->requestBase != "") {
            $this->changeRequestBase($requestBase);
        } else {
            $this->requestBase = $requestBase;
            $this->request = $this->requestBase . $this->request;
        }
    }
    
    private function appendQuestionMark($value) {
        if(substr($value, -1, 1) != "?") {
            $value .= "?";
        }
        return $value;
    }
    
    private function changeRequestBase($newRequestBase) {
        if(!empty($newRequestBase)) {
            $this->request = str_replace($this->requestBase, $newRequestBase, $this->request);
            $this->requestBase = $newRequestBase;
        }
    }
    
    public function addParameter($name, $value) {
        if(!empty($name) && !empty($value)) {
            $this->appendParameter($name, $value);
        }
    }
    
    public function appendParameter($name, $value) {
        //if last character is not & or ? we add & to the end of string
        if(!in_array(substr($this->request, -1, 1), array("&", "?"))) {
            $this->request .= "&";
        }
        $this->request .= $name . "=" . $value;
    }
    
    public function addParameters(array $parameters) {
        while($value = current($parameters)) {
            $this->addParameter(key($parameters), $value);
            next($parameters);
        }
    }
    
    public static function getBasePath() {
        $uri = Environment::getHttpRequest()->getUri();
        return $uri->scheme . "://" . $uri->host . ":" . $uri->port . $uri->scriptPath;
    }
}
